package com.tintintech.sendmail.helper;

import java.net.ConnectException;
import java.util.List;
import java.util.Map;

import com.tintintech.sendmail.Config;
import com.tintintech.sendmail.protocol.MimeMessage;
import com.tintintech.sendmail.protocol.SmtpCommand;
import com.tintintech.sendmail.util.MailBoxConstants;
import com.tintintech.sendmail.util.MailStat;
import com.tintintech.sendmail.util.PrimaryKey;
import com.tintintech.sendmail.util.SmtpServer;

public final class SendTask implements Runnable {

	private Map<String, String> box;
	public SendTask(Map<String, String> mailBox){
		this.box = mailBox;
	}
	private boolean send(Map<String, String> mailer) {
		
		final String toemail = mailer.get(MailBoxConstants.TO_EMAIL);
		if (toemail == null) {
			return false;
		}
		List<String> ipList = DNSHelper.getTargetServerOfPriority(DNSHelper.getMxRecords(toemail));
		int size = ipList.size();
		if (size == 0) {
			return false;
		}
		final String target = ipList.get(size - 1);
		if (target == null) {
			return false;
		}
		SmtpServer server = new SmtpServer(target, toemail);
		if (!server.getSocket().isConnected()) {
			return false;
		}
		try {
			SmtpCommand cmd = new SmtpCommand(server, new MimeMessage(mailer, Config.GLOBALS.get("charset")));
			return cmd.sendMessage();
		} catch (ConnectException conne) {
			System.out.println("socket-connect-err");
		} catch (Throwable tae) {
			System.out.println("send-exception");
			tae.printStackTrace();
		}
		
		return false;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		try {
			final String status = this.box.get("status");
			if (send(this.box)) {
				MailStat.MAIL_SEND_SUCCESS_NUM.incrementAndGet();
				if ("#1".equals(status)) {
					MailStat.SEND_SUCCESS_NUM_1.incrementAndGet();
				} else {
					MailStat.SEND_SUCCESS_NUM_2.incrementAndGet();
				}
			} else {
				if ("#1".equals(status)) {
					final String json = DataHelper.JSON.encode(this.box);
					DataHelper.SEND_FAILED_MAP.put(PrimaryKey.UUID() + "#1", json);
					MailStat.SEND_FAILED_NUM_1.incrementAndGet();
				} else {
					MailStat.SEND_FAILED_NUM_2.incrementAndGet();
				}
			}
		} catch (Throwable e) {
//			MailStat.MAIL_DISCARD_NUM_1.incrementAndGet();
		} finally {
			MailStat.MAIL_DISCARD_NUM_2.incrementAndGet();
		}
	}

}
